#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <assert.h>
#include <semaphore.h>
#include <fcntl.h>

#define IPCKEY 0x100

void* attach_shm_buf(void);
sem_t* attach_sem(void);

int main()
{
    unsigned char* shm_buf = attach_shm_buf();
    sem_t* sem = attach_sem();
    int a[2];
    while(1)
    {
        sem_wait(sem);
        memcpy(a, shm_buf, 8);
        sem_post(sem);

        printf("%d, %d.\n", a[0], a[1]);
    
        if(a[0] != a[1])
            break;
    }

    return 0;
}


void* attach_shm_buf(void)
{
    void* buf;

    #define SHM_SIZE    102400
    int shm_id = shmget(IPCKEY, SHM_SIZE, 0640|IPC_EXCL);
    assert(shm_id != -1);

    buf = shmat(shm_id, NULL, 0);

    return buf;
}


sem_t* attach_sem(void)
{
    sem_t* sem ;

    int flag = O_RDWR ;
    sem = sem_open("test1", 0);
    assert(NULL != sem);

    printf("======%s OK.\n", __FUNCTION__);

    return sem;
}
